#include <QSize>
#include <QBrush>
#include "DataModel.h"
#include "RequestDescriptor.h"
#include "DataTable.h"
#include "ModTimeline.h"
#include "scImpl.h"

#define FCT "ModTimeline::ModTimeline"
ModTimeline::ModTimeline(PkType entityId, PkType ik, QObject * parent) :
	ModTable(entityId, parent), ik(ik)
{
	if(dt.getDomain()!=DOMAIN_DATATL)
		throw new AppException(FCT ": ModTimeline can only be used for DOMAIN_DATATL", true);
	rq=Request(entityId, ik, true);
	emit headerDataChanged(Qt::Vertical, 0, rowCount(QModelIndex())-1);
	RequestDescriptor * rd(new RequestDescriptor(rq));
	transId=DataModel::get()->requestData(rd);
	if(!transId)
		ModTimeline::mapRowsSl(0);
}

#undef FCT
#define FCT "ModTimeline::~ModTimeline"
ModTimeline::~ModTimeline()
{
}

#undef FCT
#define FCT "ModTimeline::data(i)"
QVariant ModTimeline::data(const QModelIndex & index, int role) const
{
	// ctrc(Trc::LOOP,APP,FCT)<<"role "<<role<<endl;
	switch(role)
	{
	case Qt::DisplayRole:
		return QVariant(ModTable::data(index.column(), rowMap.at(index.row())));
	case Qt::BackgroundRole:
	{
		if(index.row()==currentRow)
			return QVariant(QBrush(QColor(241, 243, 255)));
		break;
	}
	default:
		break;
	}
	return ModTable::data(index, role);
}

#undef FCT
#define FCT "ModTimeline::mapRowsSl"
void ModTimeline::mapRowsSl(unsigned long transactionId)
{
	if(transactionId && transactionId!=transId)
	{
		ctrc(Trc::LOOP,APP,FCT)<<"skipped trans "<<transactionId<<" waiting for "<<transId<<endl;
		return;
	}
	if(transactionId)
		transId=0;
	rowMap.clear();
	DOsCIkIdx & iks(dt.getPayload().dos.get<DataObject::IkTag>());
	int i(0);
	TimeType dl(DataModel::get()->getDeadlineUTC());
	DOsCIkIdx::const_iterator end(iks.upper_bound(ik));
	for(DOsCIkIdx::const_iterator it(iks.lower_bound(ik)); it!=end; ++it)
	{
		ctrc(Trc::LOOP,APP,FCT)<<"map row "<<i<<" to time-span "<<it->getIks()<<"-"<<it->getIks2()<<" PK "<<it->getPk()<<endl;
		rowMap.push_back(it->getPk());
		if(it->getIks()<=dl && it->getIks2()>dl)
			currentRow=i;
		++i;
	}
	emit dataChanged(index(0, 0), index(rowCount(QModelIndex())-1, columnCount(QModelIndex())-1));
}

#undef FCT
#define FCT "ModTimeline::setTouched"
void ModTimeline::setTouched()
{
	ctrc(Trc::LOOP,APP,FCT)<<"touching "<<rq<<endl;
	ModTable::setTouched();
	dt.getPayload().setTouched(rq);
}
